<template>
  <div class="login">
    <div class="log-box">
      <h3>系统登录</h3>

      <el-form ref="formLogin" :model="loginForm" :rules="rules" status-icon>
        <el-form-item prop="name">
          <el-input v-model="loginForm.name" prefix-icon="iconfont icon-user" type="text"></el-input>
        </el-form-item>

        <el-form-item prop="pwd">
          <!-- .native:给组件绑定原生事件 -->
          <!-- 动态 -->
          <el-input :type="pwdstatus?'password':'text'" @click.native="cut" v-model="loginForm.pwd" prefix-icon="iconfont icon-mima" :suffix-icon="pwdstatus?'iconfont icon-biyanjing':'iconfont icon-yanjing-zhengyan'"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" class="btn">登录</el-button>
        </el-form-item>
      </el-form>

    </div>

  </div>
</template>

<script>
import { login_api } from "@/api/user.js";
import storage from "@/utils/storage.js";
export default {
  data() {
    return {
      loginForm: {
        name: "",
        pwd: "",
      },
      pwdstatus: true,
      rules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    onSubmit() {
      //同步异步---》async  awite代替axios的.then
      this.$refs.formLogin.validate(async (valid) => {
        if (valid) {
          let res = await login_api({
            account: this.loginForm.name,
            password: this.loginForm.pwd,
          });
          //对象的解构
          //token--->当前用户的身份令牌
          let { code, role, token } = res.data;
          if (code === 0) {
            storage.setSession("tk", token);
            this.$router.push("/home");
            //将token放入请求拦截器中
          }
        } else {
          return false;
        }
      });
    },

    //事件委派
    cut(e) {
      if (e.target.className.includes("yanjing")) {
        this.pwdstatus = !this.pwdstatus;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 100%;
  background-color: #2d3a4b;
  display: flex;
  justify-content: center;
  align-items: center;
}
.log-box {
  width: 500px;
  height: 300px;
  padding: 0 20px;
  // background-color: #fff;
  h3 {
    text-align: center;
    line-height: 60px;
    color: #fff;
    margin-bottom: 10px;
  }
  .btn {
    width: 100%;
    margin-top: 10px;
  }
}
</style>